import fs from 'fs-extra';
import { Ancestor, IAdditionalMsg } from "./Ancestor.js";
import { env } from "./env.js";
import { SSHClient } from "./tools/SSHClient.js";
import { ConnectConfig } from 'ssh2';
import { sendBuildFailureAlert } from './tools/alert.js';

export class SvrFootman extends Ancestor {
    private conclusion: string = '';
    private additionalMessages: IAdditionalMsg[] = [];

    public async awake(): Promise<boolean> {
        return true;
    }

    public async start(): Promise<void> {
        if (this.cmdOption.task === 'UpdateSvrRes') {
            await this.updateSvrRes();
        } else {
            console.error(`Not support task: ${this.cmdOption.task}`);
            process.exit(1);
        }
    }

    private async updateSvrRes() {
        const hostInfo = await this.getSvrHostInfo();
        if (!hostInfo) {
            console.error('svr host info not found!');
            process.exit(1);
        }
        const ssh = new SSHClient();
        await ssh.connect(hostInfo);
        const res = await ssh.exec(`autobuilder|H5_DouPoMini_CY|upres|DEPLOY_RES|RELOAD_ZONE`);
        if (!res.includes('FYGAMEBUILDER_FINISH_SUCCESS')) {
            await sendBuildFailureAlert('命令执行似乎失败了');
            process.exit(1);
        }
    }

    private async getSvrHostInfo(): Promise<ConnectConfig> {
        // 获取机器信息
        if (!env.svrHostFile || !fs.existsSync(env.svrHostFile)) {
            console.error(`svr host file not exists: ${env.svrHostFile}`);
            process.exit(1);
        }
        const secret = await fs.readFile(env.svrHostFile, 'utf-8');
        const info = Buffer.from(secret , 'base64').toString().split(' ');

        return {
            host: info[0], 
            port: 22, 
            username: 'root', 
            password: info[1]
        };
    }

    public async getBuildConclusion(): Promise<string> {
        return this.conclusion;
    }

    public async getAdditionalMessages(): Promise<IAdditionalMsg[]> {
        return this.additionalMessages;
    }
}